package com.sys.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.sys.service.UserService;
import com.sys.service.impl.UserServiceImpl;

/**
 * @ClassName: AutoLogin 
 * @Description: TODO(对整个WEB工程过滤的自动登录filter) 
 * @author 詹金浩 
 * @date 2018年3月12日 下午6:49:46
 */
@WebFilter("/*")
public class AutoLogin implements Filter {

    /**
     * Default constructor. 
     */
    public AutoLogin() {
        // TODO Auto-generated constructor stub
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    			throws IOException, ServletException {
    	HttpServletRequest httpServletRequest = (HttpServletRequest)request;
    	
    	String userName = null;
    	String userPwd = null;
    	
		Cookie []cookies = httpServletRequest.getCookies();
		//遍历Cookie获取关于用户信息的Cookie值
		if(cookies!=null) {
			for(Cookie eCookie:cookies) {
				if(eCookie.getName().equals("cookieUsername"))
					userName = eCookie.getValue();
				if(eCookie.getName().equals("cookiePassword"))
					userPwd = eCookie.getValue();
			}
		}
		//存在用户信息的Cookie值时自动登录
		if(userName != null && userPwd != null) {
			UserService userService = new UserServiceImpl();
			Boolean b = null;
			//若携带的Cookie值和数据库中不符，自动登录失败
			try {
				b = userService.checkUserIsExist(userName, userPwd);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if(b)
				httpServletRequest.getSession().setAttribute("user", userName);
		}
		chain.doFilter(request, response);
    }
    
	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
